package com.dpj.wait_test;

import lombok.extern.slf4j.Slf4j;

@Slf4j(topic = "c.GuardedObjectDemo2")
public class GuardedObjectDemo2 {
    public static void main(String[] args) {


    }
}

//增加超时结果
class GuarddeObject{
    //结果
    private  Object response;
    //获取结果
    public Object getResponse(long timeout) throws InterruptedException {
        synchronized (this){
            //开始时间
            long start = System.currentTimeMillis();
            //经历时间
            long passedTime=0;

            while(response==null){
                //经历的时间超过了最大等待时间，退出循环
                if(passedTime>timeout){
                    break;
                }
                this.wait(timeout-passedTime);//防止虚假唤醒
                //求得经历的时间
                passedTime=System.currentTimeMillis()-start;
            }
            return response;
        }
    }

    //生成结果
    public void complete(Object object) {
        synchronized (this) {
            //给结果变量赋值
            this.response = object;
            this.notifyAll();

        }
    }
}
